<script lang="ts" setup>
import {ref} from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {uploadAvatarAPI} from '@/apis/user.js'
import {useUserStore} from '@/stores/user'

import type { UploadProps, UploadUserFile } from 'element-plus'


//用户当前头像
let oldAvatarUrl=useUserStore().userInfo.avatar

//缩略图列表
const fileList = ref<UploadUserFile[]>([
  {
    name:'oldAvatar',
    url: oldAvatarUrl,
  }
])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

// 上传前的验证
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 自定义上传方法
const uploadAvatar = async (options) => {

  const formData = new FormData();
  formData.append('file', options.file);
  formData.append('uid',useUserStore().userInfo.uid);

  const res=await uploadAvatarAPI(formData)
  if (res.code === 200) {
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(response.data.msg || '上传失败');
  }


  const userData={
    //重映射字段名
    account:useUserStore().userInfo.uid,
    password:useUserStore().userInfo.password
  }
  //更新用户信息，获取最新头像
  //必须在头像上传完成之后执行，否则不能获取到最新头像
  await useUserStore().updateUserInfo(userData)
  console.log('头像更新完成')
};

//设置只有手动保存时才上传头像
import type { UploadInstance } from 'element-plus'
const uploadRef = ref<UploadInstance>()

const submitUpload = () => {
  //console.log('upload上传头像')
  uploadRef.value!.submit()
}
// 主动暴露submitUpload方法
defineExpose({ submitUpload })

</script>

<template>
  <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :auto-upload="false"
      limit="1"

      :before-upload="beforeAvatarUpload"
      :http-request="uploadAvatar"

  >
    <el-icon><Plus /></el-icon>

    <template #tip>

    </template>

  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>


